import React, { useEffect, useState } from 'react';
import { Card, Table, Button, Space, Switch, Modal, Form, Input, Upload, message, Image } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import request from '../../utils/request';
import './index.less';

const Carousel = () => {
  const [loading, setLoading] = useState(false);
  const [banners, setBanners] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [currentBanner, setCurrentBanner] = useState(null);
  const [fileList, setFileList] = useState([]);

  // 获取轮播图列表
  const fetchBanners = async () => {
    try {
      setLoading(true);
      const res = await request.get('/api/banners');
      if (res.code === 0) {
        setBanners(res.data);
      }
    } catch (error) {
      message.error('获取轮播图列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      if (!values.image_url) {
        message.error('请先上传图片');
        return;
      }

      if (currentBanner) {
        // 编辑时保持原有的image_url
        await request.put(`/api/banners/${currentBanner.id}`, values);
        message.success('更新成功');
      } else {
        // 新增时，确保image_url存在
        await request.post('/api/banners', values);
        message.success('添加成功');
      }
      setModalVisible(false);
      fetchBanners();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个轮播图吗？',
      onOk: async () => {
        try {
          await request.delete(`/api/banners/${id}`);
          message.success('删除成功');
          fetchBanners();
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 处理状态切换
  const handleStatusChange = async (checked, record) => {
    try {
      await request.put(`/api/banners/${record.id}/status`, {
        is_show: checked ? 1 : 0
      });
      message.success('状态更新成功');
      fetchBanners();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      width: 80,
      render: (_, __, index) => index + 1  // 自动生成序号，从1开始
    },
    {
      title: '图片',
      dataIndex: 'image_url',
      width: 120,
      render: (url) => (
        <Image
          src={url}
          alt="banner"
          width={100}
          height={50}
          style={{ objectFit: 'cover' }}
          preview={{
            maskClassName: 'customize-mask',
            mask: <div>点击预览</div>
          }}
        />
      )
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 200,
    },
    {
      title: '副标题',
      dataIndex: 'subtitle',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'is_show',
      width: 100,
      render: (is_show, record) => (
        <Switch
          checked={is_show === 1}
          onChange={(checked) => handleStatusChange(checked, record)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space size="small"> 
          <Button
            type="primary"
            size="default"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="default"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  const showModal = (record = null) => {
    setCurrentBanner(record);
    form.resetFields();
    if (record) {
      form.setFieldsValue(record);
      // 设置文件列表
      setFileList([{
        uid: '-1',
        name: 'banner.jpg',
        status: 'done',
        url: record.image_url
      }]);
    } else {
      setFileList([]); // 清空文件列表
    }
    setModalVisible(true);
  };

  useEffect(() => {
    fetchBanners();
  }, []);

  return (
    <Card
      title="轮播图管理"
      className="carousel-page"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setCurrentBanner(null);
            form.resetFields();
            setFileList([]);
            setModalVisible(true);
          }}
        >
          添加轮播图
        </Button>
      }
    >
      <Table
        className="carousel-table"
        columns={columns.map(col => ({
          ...col,
          ...(col.dataIndex === 'image_url' && {
            className: 'image-cell'
          }),
          ...(col.dataIndex === 'is_show' && {
            className: 'status-switch'
          }),
          ...(col.key === 'action' && {
            className: 'action-column'
          })
        }))}
        dataSource={banners}
        rowKey="id"
        loading={loading}
        pagination={false}
        scroll={{ x: 1000 }}
        size="default"
      />

      <Modal
        title={currentBanner ? '编辑轮播图' : '添加轮播图'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        className="carousel-modal"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="image_url"
            label={
              <span>
                图片
                <span className="size-tip">(建议尺寸: 1080×360)</span>
              </span>
            }
            rules={[{ required: true, message: '请上传图片' }]}
          >
            <Upload
              action="/api/upload"
              listType="picture-card"
              maxCount={1}
              data={{ type: 'banners' }}
              fileList={fileList}
              onChange={({ file, fileList }) => {
                setFileList(fileList);
                if (file.status === 'done' && file.response) {
                  if (file.response.code === 0 && file.response.url) {
                    form.setFieldsValue({ image_url: file.response.url });
                  } else {
                    message.error('图片上传失败');
                  }
                } else if (file.status === 'error') {
                  message.error('图片上传失败');
                }
              }}
              onRemove={() => {
                form.setFieldsValue({ image_url: undefined });
                setFileList([]);
              }}
              className="upload-wrapper"
            >
              {fileList.length === 0 && (
                <div className="upload-content">
                  <UploadOutlined />
                  <div>上传</div>
                </div>
              )}
            </Upload>
          </Form.Item>
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="subtitle"
            label="副标题"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default Carousel; 